<script setup lang="ts">
import {FormRules, NForm, NGrid} from 'naive-ui'
import {ref} from 'vue'
import {StWatchWidth} from 'st-common-ui-vue3'
import StnScrollbar from "../StnScrollbar"

/**
 * 组件配置选项
 */
defineOptions({
  name: 'StnResponsiveColsForm',
})

/**
 * 组件参数
 */
const {
  model = {},
  rules = {},
  labelWidth = 'auto',
  responsive = 'self',
  labelPlacement = ['left', 'top'],
  labelResponsiveWidth = 450,
  height = 'auto',
  maxHeight = 'auto',
  alwaysScrollbarWidth = 700,
  cols = '1 700:2',
} = defineProps<{
  // 表单模型
  model?: Record<string, any>;
  // 表单规则
  rules?: FormRules;
  // 标签宽度
  labelWidth?: string | number | 'auto';
  // 响应式变化策略
  responsive?: 'self' | 'screen';
  // 标签位置，当宽度小于 labelResponsiveWidth 时，标签位置使用 labelPlacement[1]，否则使用 labelPlacement[0]
  labelPlacement?: ['left' | 'top', 'left' | 'top'];
  // 标签位置响应式变化的宽度阈值
  labelResponsiveWidth?: number;
  // 表单内容区域的高度
  height?: number | string;
  // 表单内容区域的最大高度
  maxHeight?: number | string;
  // 表单区域一直显示滚动条的宽度阈值
  alwaysScrollbarWidth?: number;
  // 表单的列配置
  cols?: number | string;
}>()

// 标签位置
const labelPlacementRef = ref<'left' | 'top'>(labelPlacement[0])

/**
 * 宽度变化处理函数
 * @param {number} width
 */
const widthChangeHandler = (width: number) => {
  labelPlacementRef.value = width <= labelResponsiveWidth ? labelPlacement[1] : labelPlacement[0]
}
</script>

<template>
  <StWatchWidth
    class="stn-responsive-cols-form"
    :strategy="responsive"
    :widthChangeHandler="widthChangeHandler"
  >
    <n-form
      :model="model"
      :rules="rules"
      :labelWidth="labelWidth"
      :label-placement="labelPlacementRef"
      require-mark-placement="right-hanging"
    >
      <StnScrollbar
        :responsive="responsive"
        :height="height"
        :max-height="maxHeight"
        :always-scrollbar-width="alwaysScrollbarWidth"
      >
        <n-grid
          :responsive="responsive"
          :cols="cols"
        >
          <slot></slot>
        </n-grid>
      </StnScrollbar>
    </n-form>
  </StWatchWidth>
</template>

<style scoped lang="scss">
.stn-responsive-cols-form {
  width: 100%;
  height: 100%;
}
</style>
